<template>
  <div class="container">
    <div class="container-content">
      <vab-query-form>
        <vab-query-form-top-panel v-if="showQuery">
          <el-form
            :inline="true"
            label-width="100px"
            :model="tableOptions.queryForm"
          >
            <el-form-item label="标题">
              <el-input
                v-model="tableOptions.queryForm.title"
                placeholder="标题"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <easy-dict-select
                ref="statusRef"
                :default-value="tableOptions.queryForm.status"
                dict-code="2224"
                show-all="Y"
                @change="handlerStatusChange"
              />
            </el-form-item>
            <el-form-item label="有效截止日期">
              <el-date-picker
                v-model="state.validTimeRange"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
                @change="handleValidTimeChange"
              />
            </el-form-item>
            <el-form-item label="发送时间">
              <el-date-picker
                v-model="state.noticeTimeRange"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
                @change="handleNoticeTimeChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="refresh-left"
                type="warning"
                @click="handleResetQuery"
              >
                重置
              </el-button>
              <el-button icon="Search" type="primary" @click="queryTableData">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-top-panel>
        <vab-query-form-left-panel :span="24">
          <el-button
            v-auth="[`notice/xz`]"
            icon="circle-plus"
            type="primary"
            @click="handleAdd"
          >
            发布公告
          </el-button>
          <el-button
            v-auth="[`notice/sc`]"
            icon="remove"
            type="danger"
            @click="handleDelete"
          >
            批量删除
          </el-button>
          <el-button
            v-auth="[`notice/gb`]"
            icon="circle-close"
            type="warning"
            @click="handleClose"
          >
            批量关闭
          </el-button>
        </vab-query-form-left-panel>
      </vab-query-form>

      <el-table
        ref="tableRef"
        v-loading="tableOptions.loading"
        border
        stripe
        :data="tableOptions.dataList"
        :height="tableOptions.height"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column
          align="center"
          show-overflow-tooltip
          type="selection"
          width="50"
        />
        <el-table-column label="序号" type="index" width="55">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="标题" prop="title" width="420">
          <template #default="{ row }">
            <el-link
              :href="'./#/cmsdetail?type=notice&id=' + row.id"
              target="_blank"
              type="primary"
            >
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="发送人"
          prop="createUserName"
          width="120"
        />
        <el-table-column
          align="center"
          label="状态"
          prop="statusDesc"
          width="80"
        />
        <el-table-column
          align="center"
          :formatter="datetimeFormat"
          label="发送时间"
          prop="createTime"
          width="160"
        />
        <el-table-column
          align="center"
          :formatter="dateFormat"
          label="有效截止日期"
          prop="validEndTime"
          width="140"
        />
        <el-table-column align="center" fixed="right" label="操作" width="250">
          <template #default="{ row }">
            <el-button
              v-auth="[`notice/xg`]"
              size="small"
              type="warning"
              @click="handleEdit(row)"
            >
              修改
            </el-button>
            <el-button
              v-auth="[`notice/sc`]"
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-button
              v-if="row.status === '0'"
              v-auth="[`notice/gb`]"
              size="small"
              type="warning"
              @click="handleClose(row)"
            >
              关闭
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="tableOptions.pagination.current"
        :layout="tableOptions.pagination.layout"
        :page-size="tableOptions.pagination.size"
        :total="tableOptions.pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <notice-edit ref="editRef" width="60%" @confirm="queryTableData" />
    </div>
  </div>
</template>
<script setup name="Notice">
import { useMessage, useMessageBox } from "@/hooks/message";
import EasyDictSelect from "@/components/dictSelect.vue";
import noticeEdit from "./components/noticeEdit.vue";
import { dateFormat, datetimeFormat } from "@/utils/common";
import {
  queryNoticeTable,
  updateNoticeClose,
  deleteNotice
} from "@/api/admin/message/notice/";
import { useTable } from "@/hooks/table";
import { getTableHeight } from "@/utils/util";

const tableRef = ref(null);
const statusRef = ref(null);
const editRef = ref(null);
const showQuery = ref(true);

const state = reactive({
  noticeTimeRange: [],
  validTimeRange: []
});

const tableOptions = reactive({
  queryForm: {
    title: "",
    status: "ALL",
    beginNoticeTime: "",
    endNoticeTime: "",
    validStartTime: "",
    validExpireTime: ""
  },
  height: showQuery
    ? getTableHeight(2, true, true) - 10
    : getTableHeight(0, true, true) - 10,
  queryFunction: queryNoticeTable,
  descs: ["create_time"],
  onReseted: function () {
    statusRef.value.setValue("ALL");
    state.noticeTimeRange = [];
    state.validTimeRange = [];
  }
});

const {
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange
} = useTable(tableOptions, tableRef);

const handleValidTimeChange = value => {
  if (value && value.length > 0) {
    tableOptions.queryForm.validStartTime = value[0];
    tableOptions.queryForm.validExpireTime = value[1];
  } else {
    tableOptions.queryForm.validStartTime = "";
    tableOptions.queryForm.validExpireTime = "";
  }
};

const handleNoticeTimeChange = value => {
  if (value && value.length > 0) {
    tableOptions.queryForm.beginNoticeTime = value[0];
    tableOptions.queryForm.endNoticeTime = value[1];
  } else {
    tableOptions.queryForm.beginNoticeTime = "";
    tableOptions.queryForm.endNoticeTime = "";
  }
};

const handlerStatusChange = val => {
  tableOptions.queryForm.status = val;
  queryTableData();
};

const handleDelete = row => {
  if (row && row.id) {
    useMessageBox()
      .confirm("确认删除公告")
      .then(async () => {
        const { msg } = await deleteNotice(row.id);
        useMessage().success(msg);
        await queryTableData();
      });
  } else {
    if (tableOptions.dataSelections.length > 0) {
      const ids = tableOptions.dataSelections.map(item => item.id).join();
      useMessageBox()
        .confirm("确认删除公告")
        .then(async () => {
          const { msg } = await deleteNotice(ids);
          useMessage().success(msg);
          await queryTableData();
        });
    } else {
      useMessage().warning("未选中任何行");
    }
  }
};

const handleClose = row => {
  if (row && row.id) {
    useMessageBox()
      .confirm("确认关闭公告")
      .then(async () => {
        const { msg } = await updateNoticeClose({
          id: row.id
        });
        useMessage().success(msg);
        await queryTableData();
      });
  } else {
    if (tableOptions.dataSelections.length > 0) {
      const ids = tableOptions.dataSelections.map(item => item.id).join();
      useMessageBox()
        .confirm("确认关闭公告")
        .then(async () => {
          const { msg } = await updateNoticeClose({ id: ids });
          useMessage().success(msg);
          await queryTableData();
        });
    } else {
      useMessage().warning("未选中任何行");
    }
  }
};

const handleAdd = () => {
  editRef.value.show();
};

const handleEdit = row => {
  if (row.id) {
    editRef.value.show(row, false);
  } else {
    useMessage().warning("未选中任何行");
  }
};
</script>
<style lang="scss" scoped></style>
